﻿using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CNKI.TPI.Web.Base
{
    public class OAAuthenticationProvider
    {
        public static bool ValidateUser(string name, string pass, string ip, out string message, out DataTable dt)
        {
            OAInfointerface client = new OAInfointerface();

            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            if (string.IsNullOrEmpty(pass))
                throw new ArgumentNullException("pass");

            dt = client.GetDtUserInfo(name, pass);
            if (dt == null || dt.Rows.Count == 0)
            {
                message = "用户名/密码不匹配";
                return false;
            }

            message = string.Empty;
            return true;
        }

        public static SYS_CMS_USER GetUserInfo(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
                return null;

            return CreateResult(dt.Rows[0]);
        }

        private static SYS_CMS_USER CreateResult(DataRow row)
        {
            string mobile = string.Empty;
            string id = GetValue(row, "ID");
            string tel = GetValue(row, "handphone");
            string uName = GetValue(row, "UserName");

            string[] array = new string[4];
            array[0] = id;
            array[1] = GetValue(row, "Depnum");
            array[2] = GetValue(row, "DepName");

            //tel中可能存有多个移动电话，以,分隔
            if (!string.IsNullOrEmpty(tel))
            {
                int p = tel.IndexOf(',');
                if (p == -1)
                    mobile = tel;
                else
                {
                    mobile = tel.Substring(0, p).Trim();
                    array[3] = tel.Substring(p + 1).Trim();
                }
            }

            string extend = string.Format("{{ \"id\": \"{0}\", \"dept\": \"{1}\", \"deptName\": \"{2}\", \"mobile\": \"{3}\" }}", array);

            SYS_CMS_USER user = new SYS_CMS_USER();
            user.Username = uName.ToLower();
            user.RealName = GetValue(row, "Name");
            user.TelePhone = mobile;
            user.Email = GetValue(row, "emailmain");
            user.BeginDate = DateTime.Now.ToString("yyyy-MM-dd");
            user.EndDate = DateTime.Now.AddYears(10).ToString("yyyy-MM-dd");
            return user;
        }

        private static string GetValue(DataRow row, string columnName)
        {
            int index = row.Table.Columns.IndexOf(columnName);
            if (index == -1)
                return string.Empty;

            object obj = row[index];
            if (obj == null)
                return string.Empty;

            return obj.ToString().Trim();
        }
    }
}
